package com.liuqi.iot.service;

import com.alibaba.fastjson.JSON;
import com.liuqi.iot.bean.dto.DeviceDTO;
import com.liuqi.iot.bean.dto.DeviceModelPublishedDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Kafka通知服务
 * 在网关、设备等发生变化时，通知网关等服务
 *
 * @author  LiuQi 2025/3/28-21:15
 * @version V1.0
 **/
@Service
public class KafkaNoticeService {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${iot.kafka.topic.notice}")
    private String noticeTopic;

    /**
     * 启动网关
     */
    public void startGateway(String gatewayId) {
        this.sendGatewayNotice(gatewayId, "start");
    }

    /**
     * 发送网关相关通知实现类
     */
    private void sendGatewayNotice(String gatewayId, String op) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("gatewayId", gatewayId);
        map.put("op", op);
        kafkaTemplate.send(noticeTopic, "gateway", JSON.toJSONString(map));
    }

    // 重启网关
    public void restartGateway(String gatewayId) {
        this.sendGatewayNotice(gatewayId, "restart");
    }

    /**
     * 停止网关
     */
    public void stopGateway(String gatewayId) {
        this.sendGatewayNotice(gatewayId, "stop");
    }

    /**
     * 模型发布
     * @param dto 模型数据
     */
    public void modelPublished(DeviceModelPublishedDTO dto) {
        kafkaTemplate.send(noticeTopic, "model", JSON.toJSONString(dto));
    }

    /**
     * 设备更新
     */
    public void sendDeviceNotice(DeviceDTO device) {
        kafkaTemplate.send(noticeTopic, "device", JSON.toJSONString(device));
    }
}
